import Foundation
import SwiftUI
import WidgetKit

public extension View {
    func widgetBackground(_ color: Color) -> some View {
        modifier(BackgroundViewModifier(color: color))
    }
    
    @ViewBuilder
    func foreground(color: Color) -> some View {
        #if os(iOS)
        if #available(iOS 15.0, *) {
            foregroundStyle(color)
        } else {
            foregroundColor(color)
        }
        #else
        if #available(macOS 14.0, *) {
            foregroundStyle(color)
        } else {
            foregroundColor(color)
        }
        #endif
    }
}

private struct BackgroundViewModifier: ViewModifier {
    
    let color: Color
    
    func body(content: Content) -> some View {
        #if os(iOS)
        if #available(iOS 17.0, *) {
            return content
            .containerBackground(for: .widget) {
                color.edgesIgnoringSafeArea(.all)
            }
        } else {
            return ZStack {
                color.edgesIgnoringSafeArea(.all)
                content.padding()
            }
        }
        #else
        if #available(macOS 14.0, *) {
            return content
            .containerBackground(for: .widget) {
                color.edgesIgnoringSafeArea(.all)
            }
        } else {
            return ZStack {
                color.edgesIgnoringSafeArea(.all)
                content.padding()
            }
        }
        #endif
    }
}
